#include <QMessageBox>
#include <QtNetwork>

#include <stdlib.h>

#include "sve_server.h"

sve_server::sve_server(QWidget *parent)
    : tcpServer(0), networkSession(0)
{
        fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
                 << tr("You've got to think about tomorrow.")
                 << tr("You will be surprised by a loud noise.")
                 << tr("You will feel hungry again in another hour.")
                 << tr("You might have mail.")
                 << tr("You cannot kill time without injuring eternity.")
                 << tr("Computers are not intelligent. They only think they are.");
}

void sve_server::serverOpen(QWidget *parent){

    tcpServer = new QTcpServer(parent);

    QHostAddress myIP = QHostAddress("192.168.0.1");
    printf("ip: %u", myIP.toIPv4Address());

    if (!tcpServer->listen(myIP,23000)) {
        QMessageBox::critical(parent, tr("Fortune Server"),
                              tr("Unable to start the server: %1.")
                              .arg(tcpServer->errorString()));
        //close();
        return;
    }

    QObject::connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));
}

void sve_server::serverClose(){
    networkSession->close();
}




void sve_server::sendFortune()
{

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);

    out << (quint16)0;
    out << fortunes.at(qrand() % fortunes.size());
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    QObject::connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->disconnectFromHost();
}
